import * as moment from 'moment';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Type, CompilerOptions, NgModuleRef } from '@angular/core';
import * as _ from 'lodash';
import { UtilsService } from '@abp/utils/utils.service';
import { UrlHelper } from '@shared/helpers/UrlHelper';
import { AppConsts } from '@shared/AppConsts';
import { AppAuthService } from '@shared/common/auth/app-auth.service';

export class AppPreBootstrap {

    static run(callback: () => void): void {
        AppPreBootstrap.getApplicationConfig(() => {
            // callback();
            AppPreBootstrap.getUserConfiguration(callback);
        });
    }

    static bootstrap<TM>(moduleType: Type<TM>, compilerOptions?: CompilerOptions | CompilerOptions[]): Promise<NgModuleRef<TM>> {
        return platformBrowserDynamic().bootstrapModule(moduleType, compilerOptions);
    }

    private static getApplicationConfig(callback: () => void) {
        return abp.ajax({
            url: 'assets/appconfig.json',
            method: 'GET',
            headers: {
            }
        }).done(result => {

            AppConsts.clientBaseUrlFormat = result.clientBaseUrl;
            AppConsts.serverBaseUrlFormat = result.serverBaseUrl;
            AppConsts.arcgisMapUrl = result.arcgisMapUrl;
            AppConsts.arcgisMapServerUrl = result.arcgisMapServerUrl;
            AppConsts.arcgisStyleUrl = result.arcgisStyleUrl;
            AppConsts.wsHost = result.wsHost;
            AppConsts.clientBaseUrl = result.clientBaseUrl.replace(AppConsts.tenancyNamePlaceHolderInUrl + '.', '');
            AppConsts.serverBaseUrl = result.serverBaseUrl.replace(AppConsts.tenancyNamePlaceHolderInUrl + '.', '');

            callback();
        });
    }




    private static getUserConfiguration(callback: () => void): JQueryPromise<any> {

        const cookieLangValue = abp.utils.getCookieValue('Abp.Localization.CultureName');
        const token = abp.auth.getToken();

        const requestHeaders = {
            '.AspNetCore.Culture': ('c=' + cookieLangValue + '|uic=' + cookieLangValue)
        };

        if (token) {
            requestHeaders['Authorization'] = 'Bearer ' + token;
        }

        return abp.ajax({
            url: AppConsts.serverBaseUrl + '/api/siiat/v1/getall',
            method: 'GET',
            headers: requestHeaders
        }).done(result1 => {
           const result = result1.result;
            $.extend(true, abp, AppConsts.staticJson, result);

            // abp.clock.provider = this.getCurrentClockProvider(result.clock.provider);

            moment.locale(abp.localization.currentLanguage.name);
            (window as any).moment.locale(abp.localization.currentLanguage.name);

            // if (abp.clock.provider.supportsMultipleTimezone) {
            //     moment.tz.setDefault(abp.timing.timeZoneInfo.iana.timeZoneId);
            //     (window as any).moment.tz.setDefault(abp.timing.timeZoneInfo.iana.timeZoneId);
            // }

            abp.event.trigger('abp.dynamicScriptsInitialized');
            callback();
        });
    }

    private static getCurrentClockProvider(currentProviderName: string): abp.timing.IClockProvider {
        if (currentProviderName === 'unspecifiedClockProvider') {
            return abp.timing.unspecifiedClockProvider;
        }

        if (currentProviderName === 'utcClockProvider') {
            return abp.timing.utcClockProvider;
        }

        return abp.timing.localClockProvider;
    }


    private static setEncryptedTokenCookie(encryptedToken: string) {
        new UtilsService().setCookieValue(AppConsts.authorization.encrptedAuthTokenName,
            encryptedToken,
            new Date(new Date().getTime() + 365 * 86400000), // 1 year
            abp.appPath
        );
    }
}
